<template>
  <el-tabs v-model="activeName"
           @tab-click="handleClick">
    <el-tab-pane label="专利录入"
                 name="0">

      <div class="app-container">
        <!-- hg 先注释掉rules,便于开发 -->
        <!--   -->
        <span>专利信息</span>
        <el-divider />
        <el-form :label-position="labelPosition"
                 ref="patentObj"
                 :model="patentObj"
                 :inline="true"
                 v-show="showSearch"
                 label-width="80px">
          <el-row :gutter="10"
                  type="flex">

            <el-col :span="8"
                    :offset="3">

              <el-form-item label="专利id">
                <el-input v-model="patentObj.patentId"
                          size="mini"
                          disabled
                          placeholder="系统生成"></el-input>
              </el-form-item>

              <el-form-item label="专利编号"
                            prop="empNo">
                <el-input v-model="patentObj.patentNo"
                          placeholder="系统生成"
                          disabled
                          clearable
                          size="mini" />
              </el-form-item>

              <el-form-item label="专利名称">
                <el-input v-model="patentObj.patendName"
                          size="mini"
                          placeholder="请输入专利名称"></el-input>
              </el-form-item>

              <el-form-item label="专利类型">
                <el-select v-model="patentObj.patendTypeId"
                           placeholder="请选择"
                           size='mini'>
                  <el-option v-for="dict in dict.type.ipms_patend_type"
                             :key="dict.value"
                             :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="客户id">
                <el-input v-model="patentObj.customerId"
                          size="mini"
                          disabled
                          placeholder="路由传参"></el-input>
              </el-form-item>

            </el-col>
            <!-- 第二列col -->
            <el-col :span="8">
              <h2>上传图标</h2>
              <el-upload class="avatar-uploader"
                         action="http://oss-cn-chengdu.aliyuncs.com"
                         v-model="Addfrom.url"
                         :http-request="_uploadImg"
                         :multiple=true
                         :before-upload="handleBeforeUpload"
                         :limit="8">
                <img v-if="Addfrom.url"
                     :src="Addfrom.url"
                     :width="100"
                     :height="100"
                     class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>

            </el-col>
            <!-- 第三列 -->
            <el-col :span="8">

              <!-- 上传文件 -->
              <h2>上传材料</h2>
              <el-upload class="avatar-uploader"
                         action="http://oss-cn-chengdu.aliyuncs.com"
                         v-model="Addfrom.url"
                         :http-request="_uploadFile"
                         :multiple=true
                         :before-upload="handleBeforeUpload"
                         :limit="8">
                <img v-if="1==2"
                     :src="Addfrom.url"
                     :width="50"
                     :height="50"
                     class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <br>
              <br>
              <br>
              <div>
                <el-button type="primary"
                           plain
                           icon="el-icon-plus"
                           size="medium"
                           @click="submitPatentForm">保存</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>

        <span>+发明人</span>
        <el-divider />
        <el-form :label-position="labelPosition"
                 ref="inventorObj"
                 :model="inventorObj"
                 :inline="true"
                 v-show="showSearch"
                 label-width="80px">
          <el-row :gutter="10"
                  type="flex">

            <el-col :span="5"
                    :offset="9">

              <el-form-item label="发明人id">
                <el-input v-model="inventorObj.inventorId"
                          size="mini"
                          disabled
                          placeholder="系统生成"></el-input>
              </el-form-item>

              <el-form-item label="发明人姓名">
                <el-input v-model="inventorObj.inventorName"
                          size="mini"
                          placeholder="请输入发明人姓名"></el-input>
              </el-form-item>

              <el-form-item label="发明人证件号码"
                            label-width="10">
                <el-input v-model="inventorObj.inventorNo"
                          size="mini"
                          placeholder="请输入发明人证件号码"></el-input>
              </el-form-item>

              <el-form-item label="专利id">
                <el-input v-model="inventorObj.patentId"
                          size="mini"
                          disabled
                          placeholder="+专利信息生成"></el-input>
              </el-form-item>

              <div>
                <el-button type="primary"
                           plain
                           icon="el-icon-plus"
                           size="medium"
                           @click="submitInventorForm">保存</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>

        <span>+申请人</span>
        <el-divider />
        <el-form :label-position="labelPosition"
                 ref="applicantObj"
                 :model="applicantObj"
                 :inline="true"
                 v-show="showSearch"
                 label-width="80px">
          <el-row :gutter="10"
                  type="flex">

            <el-col :span="5"
                    :offset="9">

              <el-form-item label="申请人id">
                <el-input v-model="applicantObj.applicantId"
                          size="mini"
                          disabled
                          placeholder="系统生成"></el-input>
              </el-form-item>

              <el-form-item label="申请人姓名">
                <el-input v-model="applicantObj.applicantName"
                          size="mini"
                          placeholder="请输入申请人姓名"></el-input>
              </el-form-item>

              <el-form-item label="申请人证件号码"
                            label-width="10">
                <el-input v-model="applicantObj.applicantNo"
                          size="mini"
                          placeholder="请输入申请人证件号码"></el-input>
              </el-form-item>

              <el-form-item label="专利id">
                <el-input v-model="applicantObj.patentId"
                          size="mini"
                          disabled
                          placeholder="+专利信息生成"></el-input>
              </el-form-item>

              <div>
                <el-button type="primary"
                           plain
                           icon="el-icon-plus"
                           size="medium"
                           @click="submitApplicantForm">保存</el-button>
              </div>
            </el-col>

          </el-row>
        </el-form>
      </div>
    </el-tab-pane>

    <el-tab-pane label="签署合同"
                 name="1">
      <div class="app-container">

        <el-form :label-position="labelPosition"
                 ref="contractObj"
                 :model="contractObj"
                 :inline="true"
                 v-show="showSearch"
                 label-width="80px">
          <el-row :gutter="10"
                  type="flex">

            <el-col :span="5"
                    :offset="9">

              <el-form-item label="合同id">
                <el-input v-model="contractObj.contractId"
                          size="mini"
                          disabled
                          placeholder="系统生成"></el-input>
              </el-form-item>

              <el-form-item label="合同编号">
                <el-input v-model="contractObj.contractNo"
                          size="mini"
                          disabled
                          placeholder="系统生成"></el-input>
              </el-form-item>

              <el-form-item label="客户id（甲方）">
                <el-input v-model="contractObj.customerId"
                          size="mini"
                          disabled
                          placeholder="路由传参"></el-input>
              </el-form-item>

              <el-form-item label="员工id（乙方）">
                <el-input v-model="contractObj.empId"
                          size="mini"
                          disabled
                          placeholder="系统获取"></el-input>
              </el-form-item>

              <el-form-item label="业务类型">
                <el-select v-model="contractObj.contractCaseTypeId"
                           placeholder="请选择"
                           size='mini'>
                  <el-option v-for="dict in dict.type.ipms_contract_case_type"
                             :key="dict.value"
                             :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="代理服务费">
                <el-input v-model="contractObj.contractServiceCost"
                          size="mini"
                          placeholder="请输入代理服务费（人民币）"></el-input>
              </el-form-item>

              <el-form-item label="官方费用">
                <el-input v-model="contractObj.contractThirdCost"
                          size="mini"
                          placeholder="请输入官方费用（人民币）"></el-input>
              </el-form-item>

              <el-form-item label="专利id">
                <el-input v-model="contractObj.patendId"
                          size="mini"
                          disabled
                          placeholder="+专利信息生成"></el-input>
              </el-form-item>

              <el-form-item label="合同状态">
                <el-select v-model="contractObj.contractStatusId"
                           placeholder="请选择"
                           size='mini'>
                  <el-option v-for="dict in dict.type.ipms_contract_status"
                             :key="dict.value"
                             :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>

              <div>
                <el-button type="primary"
                           plain
                           icon="el-icon-plus"
                           size="medium"
                           @click="submitContractForm">保存</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>

      </div>
    </el-tab-pane>

    <el-tab-pane label="合同预览"
                 name="2">
      <div class="app-container">
        <button @click="backContractPool()">返回合同池</button><br><br>
        <img v-if="1==1"
             :src="previewURL"
             :width="1328"
             :height="1452"
             class="avatar">
      </div>
    </el-tab-pane>

  </el-tabs>
</template>

<script>
//引入题目列表方法
import {
  listCase,
  addCase,
  updateCase,
  delCase,
  detailCase,
  addApplicant,
  findApplicant,
} from '@/api/patent/Bao'

import {
  addInventor, //新增发明人
  findInventorList,
  feignAddInventor, //feign新增
  addPatent, //新增专利
  findPatentList, //查找全部专利
  sendEmail,      //发送邮件
} from '@/api/patent/ican'

// @iCAN Vue直传OSS文件
import { uploadFile, uploadImg } from '@/api/patent/alioss'
import{addContract}from '@/api/contract/lu' 
import{getCustomer}from '@/api/crm/crm' 

export default {
  //声明使用字典
  dicts: [
    //专利类型字典
    'ipms_patend_type',
    'ipms_contract_case_type',
    'ipms_contract_status',
  ],
  data() {
    return {
      //合同预览
      previewURL:
        'https://aliyun-shelly-oss.oss-cn-chengdu.aliyuncs.com/ipms/合同预览.imps',
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      // form: {},

      // 列信息
      columns: [
        { key: 0, visible: true },
        { key: 1, visible: true },
        { key: 2, visible: true },
        { key: 3, visible: true },
        { key: 4, visible: true },
        { key: 5, visible: true },
        { key: 6, visible: true },
        { key: 7, visible: true },
      ],

      //
      formatPatentType: undefined,

      /* Tab标签 */
      activeName: '0',

      /* 查询参数 */
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caseNo: '',
        patendNo: undefined,
        patendName: undefined,
        patendTypeId: undefined,
        customerContact: undefined,
        caseStatusId: undefined,
        empSalesName: undefined,
      },

      /* 案件数据 */
      caseList: [],

      //多选框编号
      Nos: [],

      //修改案件参数（案件状态、撰稿人）
      caseModify: {
        caseNos: [],
        caseStatusId: '1',
        caseEmpSalesId: undefined,
        caseEmpWriterId: undefined,
        caseReasonsRejection: undefined,
      },

      //vue oss直传第二版
      fileList: [],
      Addfrom: {
        url: '',
      },

      //发明人
      inventorObj: {
        inventorId: null,
        inventorName: null,
        inventorNo: null,
        patentId: null,
      },

      //申请人
      applicantObj: {
        applicantId: undefined,
        applicantName: undefined,
        applicantNo: undefined,
        patentId: undefined,
      },
      //专利
      patentObj: {
        /*专利主键id*/
        patendId: null,
        /*专利名称*/
        patendName: null,
        /*专利编号*/
        patendNo: null,
        /*专利类型字典*/
        patendTypeId: null,
        /*客户id*/
        customerId: null,
        /*专利材料*/
        patendMaterials: null,
        /*专利图标*/
        patendIcon: null,
      },
      //当前客户id
      curCustomerId: 0,
      //当前专利id
      curPatentId: 0,

      //合同 
      contractObj:{
        contractId: null, //合同id(系统)
        contractNo: null, //合同编号（系统）
        customerId: null, //客户id
        empId:null,       //员工id（系统）
        contractCaseTypeId:null,  //业务类型字典
        contractServiceCost:null, //代理服务费
        contractThirdCost:null,   //官方费用
        patendId:null,            //专利id
        contractStatusId:null     //合同状态 
      },
       //当前客户邮箱
      curCustomerEmail: null,
    }
  },

  //@iCAN 计算属性 获取vuex全局customerId
  computed: {
    customerId() {
      return this.$store.state.user.customerId
    },
  },

  //@ iCAN 监听vuex全局customerId
  watch: {
    customerId: {
      handler: function (val, oldVal) {
        if (val != 9999) {
          this.curCustomerId = val
          //去拿客户邮箱
          getCustomer(this.curCustomerId).then((resp)=>{
            this.curCustomerEmail = resp.data.customerEmail;
          })
        } else {
        }
      },
      // 刷新页面时立即执行
      immediate: true,
    },
  },

  created() {

    // this.getCaseList()

    //查找发明人
    // findInventorList(66).then((resp) => {
    //   console.log(resp)
    // })

    // 邮件
    // let address = '547514399@qq.com';
    // let msg = '哥哥，约么?';
    // sendEmail(address,msg).then((resp)=>{
    //   console.log(resp);
    // })
  },

  methods: {
    /* Tabs标签 */
    handleClick(tab, event) {
      console.log(tab, event)
      this.queryParams.caseStatusId = this.activeName
      console.log('activeName:', this.activeName)
      //this.getCaseList()
    },

    // 表单重置
    reset() {},

    /** 搜索按钮操作 */
    handleQuery() {
      listCase(this.queryParams).then((response) => {
        this.caseList = response.rows
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        caseNo: undefined,
        patendNo: undefined,
        patendName: undefined,
        patendTypeId: undefined,
        customerContact: undefined,
        caseStatusId: undefined,
        empSalesName: undefined,
      }
      this.getCaseList()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.Nos = selection.map((item) => item.caseNo)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /* 业务方法 */
    //案件列表
    getCaseList() {
      listCase(this.queryParams).then((response) => {
        this.caseList = response.rows
        this.total = response.total
      })
    },

    //分配撰稿人点击事件
    update(row) {
      this.caseModify.caseNos = row.caseNo || this.Nos
      updateCase(this.caseModify).then((response) => {
        console.log('修改案件成功')
      })
    },

    //案件删除
    del() {
      delCase(this.Nos).then((response) => {
        console.log('删除案件成功')
      })
    },

    //案件详情
    detailById() {
      detailCase(777).then((response) => {
        console.log('案件详情：', response)
      })
    },

    //第二版上传文件之前
    handleBeforeUpload(file) {
      const isJPEG = file.name.split('.')[1] === 'jpeg'
      const isJPG = file.name.split('.')[1] === 'jpg'
      const isPNG = file.name.split('.')[1] === 'png'
      const isWEBP = file.name.split('.')[1] === 'webp'
      const isGIF = file.name.split('.')[1] === 'gif'
      const isLt500K = file.size / 1024 / 1024 / 1024 / 1024 < 4
      if (!isJPG && !isJPEG && !isPNG && !isWEBP && !isGIF) {
        //this.$message.error('上传图片只能是 JPEG/JPG/PNG 格式!')
      }
      if (!isLt500K) {
        // this.$message.error('单张图片大小不能超过 4mb!')
      }
      // return (isJPEG || isJPG || isPNG || isWEBP || isGIF) && isLt500K
      return true
    },

    //上传图片
    _uploadImg(file) {
      uploadImg(file.file).then((resp) => {
        this.Addfrom.url = resp
        console.log('图片地址：', resp)
        this.$message.success('专利图标上传成功')
        this.patentObj.patendIcon = resp
      })
    },

    //上传文件
    _uploadFile(file) {
      // then抓alioss.js的Promise resolve  => async wait
      uploadFile(file.file).then((resp) => {
        console.log('文件地址：', resp)
        this.$message.success('专利资料文件上传成功')
        this.patentObj.patendMaterials = resp
      })
    },
    //新增专利
    submitPatentForm() {
      this.patentObj.customerId = this.curCustomerId
      addPatent(this.patentObj).then((resp) => {
        console.log(resp.data.patendId)
        this.curPatentId = resp.data.patendId
        this.$message.success('新增专利成功')
      })
    },
    //新增发明人
    submitInventorForm() {
     
      //新增发明人
      //  addInventor(this.inventorObj).then((resp)=>{
      //    console.log(resp);
      //  });

      //走feign
      this.inventorObj.patentId = this.curPatentId;
      feignAddInventor(this.inventorObj).then((resp) => {
        console.log('feign新增', resp)
         this.$message.success('新增发明人成功')
      })
    },

    //新增申请人
    submitApplicantForm() {
      this.applicantObj.patentId = this.curPatentId;
      addApplicant(this.applicantObj).then((response) => {
        this.$message.success('添加申请人成功')
      })
    },

    // 新增合同
    submitContractForm(){
      this.contractObj.customerId = this.curCustomerId;
      this.contractObj.patendId =  this.curPatentId;
      addContract(this.contractObj).then((resp=>{
        console.log(resp);
        // this.$message.success('新增合同成功，可以去预览合同了')
        //发送邮件给客户
        sendEmail(this.curCustomerEmail,"您好，合同已生效，已在办理中~").then((resp)=>{
          this.$message.success('注意查收邮箱~');
        })
      }))
    },

    //返回合同池
    backContractPool() {
      this.$message.info('返回合同池')
      this.$router.push({ path: '/contract/pool/index' })
    },
  },
}
</script>

<style lang="stylus" scoped></style>
